package com.xrit.sunnyday.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.sunnyday.pojo.Permission;
import com.xrit.sunnyday.pojo.Role;
import com.xrit.sunnyday.pojo.User;
import com.xrit.sunnyday.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class UserDS implements UserDetailsService {
    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据前端传来的用户名查询数据库
        User userInfo = userService.findByUserName(username);
        //拥有的角色和权限的集合
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        SimpleGrantedAuthority authority = null;
        //查询拥有的角色和权限循环添加到集合
        if(null != userInfo){
            Set<Role> roles = userInfo.getRoles();
            if(null != roles){
                for (Role role : roles) {
                    //一个SimpleGrantedAuthority对应一个角色
                    authority = new SimpleGrantedAuthority(role.getKeyword());
                    //一个一个添加
                    grantedAuthorityList.add(authority);

                    Set<Permission> permissions = role.getPermissions();
                    if(null != permissions){
                        for (Permission permission : permissions) {
                            //一个SimpleGrantedAuthority对应一个权限
                            authority = new SimpleGrantedAuthority(permission.getKeyword());
                            //一个一个添加
                            grantedAuthorityList.add(authority);
                        }
                    }
                }
            }
            //将securitiy需要的用户信息添加的USER对象并返回
            return new org.springframework.security.core.userdetails.User(username,userInfo.getPassword(),grantedAuthorityList);
        }

        return null;
    }

//    private User findByUserName(String username){
//        if("kang".equals(username)){
//            User userInfo = new User();
//            userInfo.setUsername("kang");
//            userInfo.setPassword("$2a$10$.AumI0r2Dd4gwx5KizWptuydNeFYnl5952LrJUa.cq6ZH0aLpUlAm");
//            return userInfo;
//        }
//        return null;
//    }
//
//    public static void main(String[] args) {
//        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
//        System.out.println(encoder.encode("6666"));
//        //$2a$10$.AumI0r2Dd4gwx5KizWptuydNeFYnl5952LrJUa.cq6ZH0aLpUlAm
//    }
}
